package com.opencloud.system.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.opencloud.common.model.PageParams;
import com.opencloud.common.model.Result;
import com.opencloud.common.security.http.XRestTemplate;
import com.opencloud.system.client.model.entity.GatewayRoute;
import com.opencloud.system.client.service.IGatewayRouteClient;
import com.opencloud.system.service.GatewayRouteService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 网关智能路由
 *
 * @author: liuyadu
 * @date: 2019/3/12 15:12
 * @description:
 */
@Api(tags = "网关智能路由")
@RestController
public class GatewayRouteController implements IGatewayRouteClient {

    @Autowired
    private GatewayRouteService gatewayRouteService;
    @Autowired
    private XRestTemplate xRestTemplate;

    @ApiOperation(value = "获取路由列表", notes = "获取路由列表")
    @GetMapping("/gateway/route")
    @Override
    public Result<Page<GatewayRoute>> getPage(@RequestParam Map<String, Object> map) {
        return Result.ok().data(gatewayRouteService.findPage(new PageParams(map)));
    }

    @ApiOperation(value = "获取路由详情", notes = "获取路由详情")
    @GetMapping("/gateway/route/info")
    @Override
    public Result<GatewayRoute> get(@RequestParam("routeId") Long routeId) {
        return Result.ok().data(gatewayRouteService.getById(routeId));
    }

    @ApiOperation(value = "添加/修改路由", notes = "添加/修改路由")
    @PostMapping("/gateway/route/save")
    @Override
    public Result<Long> save(@RequestBody GatewayRoute gatewayRoute) {
        if (gatewayRoute.getRouteId() == null) {
            gatewayRouteService.add(gatewayRoute);
        } else {
            gatewayRouteService.update(gatewayRoute);
        }
        // 刷新网关
        xRestTemplate.refreshGateway();
        return Result.ok();
    }

    @ApiOperation(value = "移除路由", notes = "移除路由")
    @PostMapping("/gateway/route/remove")
    @Override
    public Result remove(@RequestParam("routeId") Long routeId) {
        gatewayRouteService.remove(routeId);
        // 刷新网关
        xRestTemplate.refreshGateway();
        return Result.ok();
    }
}
